<template>
  <div
    style="
      position: absolute;
      top: 0;
      left: 0;
      margin: 0;
      padding: 0;
      background: red;
      width: 100%;
      height: 100%;
      background-repeat: no-repeat;
      background-size: cover;
      background-position: center;
      display: flex;
    "
    :style="{
      background: 'url(' + backgroundImage + ')',
    }"
  >
    <div
      style="
        position: absolute;
        top: 0;
        left: 0;
        background-repeat: no-repeat;
        background-size: auto;
        background-position: center;
        width: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
      "
    >
      <img
        id="titleBar"
        src="../assets/tbg.png"
        style="width: 100%; position: absolute; top: 0px; left: 0px"
        alt=""
      />
    </div>
    <div
      style="
        flex: 3;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        color: white;
      "
      :style="{
        paddingTop: titleHeight + 10 + 'px',
        height: 'calc(100% - ' + (titleHeight + 10) + 'px' + ')',
      }"
    >
      <div
        v-for="(item, index) in programList"
        :key="index"
        style="
          display: flex;
          flex-direction: column;
          position: relative;
          margin-bottom: 20px;
        "
      >
        <div
          @click="selectProgram(index)"
          style="
            width: 100%;
            position: relative;
            display: flex;
            align-items: center;
            cursor: pointer;
            height: 60%;
          "
        >
          <div
            :style="{ top: 'calc((100% - 30px)/2)' }"
            style="
              position: absolute;
              left: 30%;
              height: 20px;
              display: flex;
              justify-content: center;
              align-items: center;
              font-size: 1vw;
              color: #00ffe1;
            "
          >
            {{ item.program_name }}
          </div>
          <img
            src="../assets/close.png"
            style="position: absolute; right: 10%; height: 30px"
            alt=""
          />
          <img
            :src="
              selectedProgram == index
                ? require('../assets/selected.png')
                : require('../assets/unselected.png')
            "
            style="width: 100%"
          />
        </div>
        <div
          v-if="selectedProgram == index"
          style="
            width: 60%;
            margin-left: 30%;
            display: flex;
            flex-direction: column;

            border: solid 2px #177a71;
          "
        >
          <div
            @click="selectSonProgram(sonIndex, sonItem)"
            v-for="(sonItem, sonIndex) in item.programs"
            :key="sonIndex"
            style="
              display: flex;
              align-items: center;

              cursor: pointer;
              padding: 10px 0;
            "
            :style="{
              background:
                selectedSonProgram == sonIndex && selectedProgram == index
                  ? 'linear-gradient(to right, transparent, #8EF96E)'
                  : 'transparent',
            }"
          >
            <div
              style="
                width: 5px;
                height: 5px;
                background: #00ffe1;
                margin: 0 20px;
              "
            ></div>
            <div>{{ sonItem.media }}</div>
          </div>
        </div>
      </div>
    </div>
    <div
      style="
        flex: 7;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
      "
      :style="{
        paddingTop: titleHeight - 50 + 'px',
        height: 'calc(100% - ' + (titleHeight - 50) + 'px' + ')',
      }"
    >
      <div
        style="
          width: 95%;
          height: 90%;
          position: relative;
          background-repeat: no-repeat;
          background-size: 100% 100%;
          background-position: center;
          display: flex;
          justify-content: center;
          align-items: center;
        "
        :style="{}"
      >
        <img
          style="width: 100%; height: 100%; position: absolute; left: 0; top: 0"
          src="../assets/border.png"
          alt=""
        />
        <div
          id="play_box"
          style="width: 95%; height: 90%; background: black"
        ></div>
      </div>

      <div
        style="
          width: 100%;
          flex: 1;
          margin: 30px 0;
          display: flex;
          flex-direction: column;
          color: #00ffe1;
        "
      >
        <div
          style="
            width: calc(100% - 200px);
            text-align: left;
            margin: 0 100px;
            display: flex;
            justify-content: space-between;
          "
        >
          <div>展厅大屏3：2343晚会</div>

          <div style="display: flex; align-items: center">
            <img
              src="../assets/voice.png"
              style="width: 30px; height: 30px"
              alt=""
            />

            <div style="width: 200px; margin-left: 20px">
              <el-slider
                v-model="volumeValue"
                :show-tooltip="false"
              ></el-slider>
            </div>
            <div style="margin-left: 20px; width: 50px">{{ volumeValue }}%</div>
          </div>
        </div>

        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: calc(100% - 200px);
            margin: 10px 100px;
          "
        >
          <img
            @click="onPlayer"
            src="../assets/play1.png"
            style="width: 50px; height: 50px; cursor: pointer"
            alt=""
          />
          <img
            src="../assets/pause1.png"
            style="width: 50px; height: 50px; cursor: pointer"
            alt=""
          />
          <img
            @click="onStop"
            src="../assets/stop1.png"
            style="width: 50px; height: 50px; cursor: pointer"
          />
          <img
            src="../assets/unMute1.png"
            style="width: 50px; height: 50px; cursor: pointer"
            alt=""
          />
          <img
            src="../assets/mute.png"
            style="width: 50px; height: 50px; cursor: pointer"
            alt=""
          />
          <img
            src="../assets/fullScreen.png"
            style="width: 50px; height: 50px; cursor: pointer"
            alt=""
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from "../axios/request";
export default {
  data() {
    return {
      titleBackgroundImage: require("../assets/tbg.png"),
      backgroundImage: require("../assets/bg.png"),
      javaResponse: "",
      javaMessage: "",
      titleHeight: null,
      programList: [],
      borderImage: require("../assets/border.png"),
      volumeValue: 0,
      selectedProgram: null,
      curSuffix: null,
      curPid: null,
      selectedSonProgram: null,
      curFid: null,
      playMode: 0,
      tokenId: null,
      socket: null,
      dsBridge: null,
      config: {
        hasAudio: true,
        isLive: true,
        MSE: true,
        WCS: false,
      },
      isPlay: false,
      playMode: null,
      easyplayer: null,
      loading: false,
      curPlayMode: null,
    };
  },
  beforeDestroy() {
    this.destroyVlcPlayer();
  },
  mounted() {
    const resizeObserver = new ResizeObserver((entries) => {
      requestAnimationFrame(() => {
        for (const entry of entries) {
          this.titleHeight = Math.ceil(entry.contentRect.height);
        }
      });
    });
    resizeObserver.observe(document.getElementById("titleBar"));
    // 注册全局回调方法供Java调用
    window.vueCallback = (data) => {
      this.javaMessage = data;
      return "Vue已收到数据"; // 可选返回值
    };
    this.dsBridge = require("dsbridge");
    this.connectWs();
    this.getProgramList();
    // this.initVlc();
    this.playCreate();
  },
  methods: {
    playCreate() {
      let container = document.getElementById("play_box");
      let that = this;
      this.easyplayer = new EasyPlayerPro(container, {
        isLive: this.config.isLive, //默认 true
        bufferTime: 0.2, // 缓存时长
        stretch: false,
        MSE: this.config.MSE,
        WCS: this.config.WCS,
        hasAudio: this.config.hasAudio,
        watermark: { text: { content: "easyplayer-pro" }, right: 10, top: 10 },
      });
      this.easyplayer.on("fullscreen", function (flag) {
        console.log("is fullscreen", id, flag);
      });
      this.easyplayer.on("playbackRate", (rate) => {
        that.easyplayer.setRate(rate);
      });

      this.easyplayer.on("playbackSeek", (data) => {
        console.log("playbackSeek", data);
      });
    },
    testDsbridge() {
      // this.dsBridge.call("test", 123);
    },
    async onStop() {
      this.isPlay = false;
      this.onDestroy().then(() => {
        this.playCreate();
        this.stopStream();
      });
    },
    onDestroy() {
      let _this = this;
      return new Promise((resolve, reject) => {
        this.easyplayer.destroy();
        this.easyplayer = null;
        setTimeout(() => {
          resolve();
        }, 100);
      });
    },
    async stopStream() {
      if (this.playMode == 1) {
        let res = await request({
          url: "/material/api/stopOnDemand",
          method: "POST",
          data: {
            command: 13,
            user_name: localStorage.getItem("user_name"),

            data: [
              {
                suffix: this.curSuffix,
              },
            ],
          },
        });
        if (res.data.status == 200) {
          console.log("已成功关闭资源点播");
        }
      } else {
        let res = await request({
          url: "/program/api/stopProgram",
          method: "POST",
          data: {
            command: 15,
            user_name: localStorage.getItem("user_name"),
            data: [
              {
                pl_id: this.curPid,
              },
            ],
          },
        });
        if (res.data.status == 200) {
          console.log("已成功关闭节目点播");
        }
      }
    },
    initWs(wsId) {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        let wsUrl = window.location.origin.replace("http://", "");
        // 实例化socket 111是固定的用户id,正式环境直接获取当前登录用户id
        this.socket = new WebSocket(
          "ws:" + "192.168.0.16:8093" + "/wsServer/" + wsId
        );
        // this.socket = new WebSocket("ws:" + wsUrl + "//wsServer/" + wsId);
        this.global.setWs(this.socket);
        let that = this;
        // 监听socket连接
        this.socket.onopen = () => {
          console.log("socket连接成功");
        };
        // 监听socket错误信息
        this.socket.onerror = () => {
          console.error("连接错误");
          this.initWs(wsId);
        };
        //监听socket消息
        this.socket.onmessage = (msg) => {
          let jsonObject = JSON.parse(msg.data);
          console.log(jsonObject);
        };
        // 监听socket关闭信息
        this.socket.onclose = (e) => {
          console.log("socket已经关闭");
        };
      }
    },
    async connectWs() {
      let res = await request({
        url: "/user/api/getRandomId",
        method: "GET",
      });
      if (res.data.status == 200) {
        this.tokenId = "preview" + res.data.data;
        this.initWs(this.tokenId);
      }
    },
    async onPlayer() {
      if (this.playMode == null || this.playMode != this.curPlayMode ||this.curPlayMode ==0) {
        this.isPlay = false;
      }
      this.playMode = this.curPlayMode;
      this.curPlayMode = null;
      if (this.playMode == 1) {
        console.log(this.curSuffix, this.curFid);
        let res = await request({
          url:
            "/material/api/" + (this.isPlay ? "onDemand" : "onDemandWithTrans"),
          method: "POST",
          data: {
            command: 12,
            user_name: "Admin",
            tokenId: this.tokenId,
            data: [
              {
                suffix: this.curSuffix,
                file_id: this.curFid,
              },
            ],
          },
        });
        if (res.data.status == 200) {
          let data = res.data.data.data;
         
            this.loading = true;
            this.playStream(res.data.data.data.flvUrl);
          
        }
      } else if (this.playMode == 0) {
        let res = await request({
          url:
            "/program/api/" + (this.isPlay ? "onDemand" : "onDemandWithTrans"),
          method: "POST",
          data: {
            command: 14,
            user_name: "Admin",
            tokenId: this.tokenId,
            data: [
              {
                pl_id: this.curPid,
              },
            ],
          },
        });
        if (res.data.status == 200) {
          let data = res.data.data.data;
        
            this.loading = true;
            this.playStream(res.data.data.data.flvUrl);
         
        }
      }
    },
    onReplay() {
      this.onDestroy().then(() => {
        this.playCreate();
        this.onPlayer();
      });
    },
    playStream(flvUrl) {
      this.isPlay = true;
      let that = this;
      setTimeout(
        (url) => {
          this.easyplayer &&
            this.easyplayer
              .play(url)
              .then(() => {
                console.log("播放");
                let hideLogo = setTimeout(() => {
                  that.loading = false;
                  clearTimeout(hideLogo);
                }, 1000);
              })
              .catch((e) => {
                console.error(e);
              });
        },
        0,
        flvUrl
      );
      this.socket.send(
        JSON.stringify({
          isPlay: this.isPlay,
          suffix: this.curSuffix,
          pl_id: this.curPid,
          file_id: this.curFid,
          playMode: this.playMode,
          user_name: localStorage.getItem("user_name"),
        })
      );
    },
    selectSonProgram(index, item) {
      // if (this.playMode != 1) {
      //   this.isPlay = false;
      // }
      console.log(item.id);
      this.curPlayMode = 1;
      this.curFid = item.id;
      this.selectedSonProgram = index;
    },
    selectProgram(index) {
      // this.isPlay = false;
      this.curPlayMode = 0;
      this.selectedProgram = index;
      this.selectedSonProgram = null;
      this.curSuffix = this.programList[index].suffix;
      this.curPid = this.programList[index].id;
    },
    destroyVlcPlayer() {},
    async getProgramList() {
      let res = await request({
        url: "/program/api/getProgramList",
        method: "POST",
        data: {
          command: 10,
          user_name: "Admin",
          data: [
            {
              id: -1,
              pl_id: -1,
            },
          ],
        },
      });
      if (res.data.status == 200) {
        this.programList = res.data.data.data;
        console.log(this.programList);
      }
    },
    initVlc() {
      let displayWin = document
        .getElementById("display")
        .getBoundingClientRect();
      const data = {
        action: "initVlc",
        payload: {
          pageWidth: window.innerWidth,
          pageHeight: window.innerHeight,
          windowWidth: displayWin.width,
          windowHeight: displayWin.height,
          windowLeft: displayWin.left,
          windowTop: displayWin.top,
        },
      };
    },
  },
};
</script>

<style scoped>
</style>